package com.mobilesales.android.database;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.util.Log;

import com.mobilesales.android.model.tasks.CyclicTask;
import com.mobilesales.android.model.tasks.Schedule;
import com.mobilesales.android.model.tasks.Task;
import com.mobilesales.android.model.tasks.TaskStatus;
import com.mobilesales.android.model.tasks.TaskType;

public class TaskManager extends ManagerBase{
	
	public TaskManager(Context c)
	{
		super(c);
	}
	
	public List<Schedule> GetScheduleList(int employeeId)
	{
     	try {
     		
     		String query = "SELECT _id"
     						+ " FROM Schedules"
     						+ " WHERE EmployeeId = " + employeeId;
     		Cursor c = db.rawQuery(query, null);
     		
     		List<Schedule> result = new ArrayList<Schedule>();
     		if (!c.moveToFirst())
     			return result;
     		
     		List<Integer> tmp = new ArrayList<Integer>();
     		while (!c.isAfterLast()){
     			tmp.add(c.getInt(c.getColumnIndex("_id")));
     			c.moveToNext();
     		}
     		c.close();
     		for (int id : tmp)
     			result.add(GetSchedule(id));	
     		return result;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     	}
     	
		return null;
	}
	
	public Schedule GetSchedule(int scheduleId)
	{
     	try {
     		
     		String query = "SELECT _id, EmployeeId, CreationDate, ModificationDate, StartTime, EndTime, StartPosLat, StartPosLon, EndPosLat, EndPosLon, RealStartTime, RealEndTime" 
							+ " FROM Schedules" 
							+ " WHERE _id = " + scheduleId;
     		Cursor c = db.rawQuery(query, null);
     		

     		if (!c.moveToFirst())
     			return null;
     		
     		Schedule result = new Schedule();
     		result.Id = c.getInt(c.getColumnIndex("_id"));
     		result.EmployeeId = c.getInt(c.getColumnIndex("EmployeeId"));
     		result.CreationDate = c.getString(c.getColumnIndex("CreationDate"));
     		result.ModificationDate = c.getString(c.getColumnIndex("ModificationDate"));
     		result.StartTime = c.getString(c.getColumnIndex("StartTime"));
     		result.EndTime = c.getString(c.getColumnIndex("EndTime"));
     		result.StartPositionLatitude = c.getDouble(c.getColumnIndex("StartPosLat"));
     		result.StartPositionLongitude = c.getDouble(c.getColumnIndex("StartPosLon"));
     		result.EndPositionLatitude = c.getDouble(c.getColumnIndex("EndPosLat"));
     		result.EndPositionLongitude = c.getDouble(c.getColumnIndex("EndPosLon"));
     		result.RealStartTime = c.getString(c.getColumnIndex("RealStartTime"));
     		result.RealEndTime = c.getString(c.getColumnIndex("RealEndTime"));
     		
     		c.close();
     		result.Tasks = GetTaskList(result.Id);
	    		  		
     		return result;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     	}
     	
		return null;
	}
	
	public boolean StoreSchedule(Schedule schedule)
	{
     	try {
     		int result;
			ContentValues cv = new ContentValues();
			if (schedule.Id == 0){
				cv.put("CreationDate",schedule.CreationDate);
			}
			cv.put("_id", schedule.Id);
			cv.put("EndPositionLatitude", schedule.EndPositionLatitude);
			cv.put("EndPositionLongitude", schedule.EndPositionLongitude);
			cv.put("EndTime", schedule.EndTime);
			cv.put("ModificationDate", schedule.ModificationDate);
			cv.put("RealEndTime", schedule.RealEndTime);
			cv.put("RealStartTime", schedule.RealStartTime);
			cv.put("StartPositionLatitude", schedule.StartPositionLatitude);
			cv.put("StartPositionLongitude", schedule.StartPositionLongitude);
			cv.put("StartTime", schedule.StartTime);
			cv.put("EmployeeId", schedule.EmployeeId);
			
			result = db.update("Schedules", cv, "_id ="+schedule.Id, null);
			if (result == 0)
				result = db.insert("Schedules", null, cv) != -1 ? 1 : 0;
			return result ==1 ? true : false;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     		return false;
     	}
	}
	
	public boolean RemoveSchedule(int scheduleId)
	{
     	try {
     		int result;
			result = db.delete("Schedules", "_id ="+scheduleId, null);
			return result == 1 ? true : false;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     		return false;
     	}
	}
	
	public boolean StartSchedule(int scheduleId, String time, double latitude, double longitude)
	{
     	try {
     		int result;
			ContentValues cv = new ContentValues();
			
			cv.put("RealStartTime", time);
			cv.put("StartPositionLatitude", latitude);
			cv.put("StartPositionLongitude", longitude);
			
			result = db.update("Schedules", cv, "_id ="+scheduleId, null);
			
			return result == 1 ? true : false;

     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     		return false;
     	}
	}

	public boolean EndSchedule(int scheduleId, String time, double latitude, double longitude)
	{
     	try {
     		int result;
			ContentValues cv = new ContentValues();
			
			cv.put("RealEndTime", time);
			cv.put("EndPositionLatitude", latitude);
			cv.put("EndPositionLongitude", longitude);
			
			result = db.update("Schedules", cv, "_id ="+scheduleId, null);
			return result == 1 ? true : false;

     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     		return false;
     	}
	}

	public Task GetTask(int taskId)
	{
     	try {
     		
     		String query = "SELECT _id, CreatorId, TaskStatusId, TaskTypeId, CreationDate, ModificationDate, StartTime, EndTime, StartPosLat, StartPosLon, EndPosLat, EndPosLon, RealStartTime, RealEndTime, ClientId, Info, Priority, ScheduleId" 
							+ " FROM Tasks" 
							+ " WHERE _id = " + taskId;
     		Cursor c = db.rawQuery(query, null);
     		

     		if (!c.moveToFirst())
     			return null;
     		
     		Task result = new Task();
     		FillTaskFromCursor(c, result);		  		
     		return result;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     	}
     	
		return null;
	}
	
	public ArrayList<Task> GetTaskList(int scheduleId)
	{
     	try {
     		String query = "SELECT _id" 
				+ " FROM Tasks" 
				+ " WHERE _id = " + scheduleId;
     		Cursor c = db.rawQuery(query, null);

	 		ArrayList<Task> result = new ArrayList<Task>();
    		if (c.moveToFirst()){
    			List<Integer> tmp = new ArrayList<Integer>();
	     		while (!c.isAfterLast()){    	     		
	     			tmp.add(c.getInt(c.getColumnIndex("_id")));
	         		c.moveToNext();
	     		}
	     		c.close();
	     		for (int id : tmp)
	         		result.add(GetTask(id));
	     	}
     		return result;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     	}
     	return null;
	}
	
	public ArrayList<Task> GetOverlayTasks(Date date)
	{
     	try {
     		DateFormat df = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
     		String queryDate = df.format(date).toString();
     		if (queryDate.startsWith("0"))
     			queryDate = queryDate.substring(0);
     		String query = "SELECT _id" 
				+ " FROM Tasks" 
				+ " WHERE CreationDate = " + queryDate;
     		Cursor c = db.rawQuery(query, null);

	 		ArrayList<Task> result = new ArrayList<Task>();
    		if (c.moveToFirst()){
    			List<Integer> tmp = new ArrayList<Integer>();
	     		while (!c.isAfterLast()){    	     		
	     			tmp.add(c.getInt(c.getColumnIndex("_id")));
	         		c.moveToNext();
	     		}
	     		c.close();
	     		for (int id : tmp)
	         		result.add(GetTask(id));
	     	}
     		return result;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     	}
     	return null;
	}
	
	public CyclicTask GetCyclicTask(int taskId)
	{
     	try {
     		
     		String query = "SELECT _id, CreatorId, TaskStatusId, TaskTypeId, CreationDate, ModificationDate, StartTime, EndTime, StartPosLat, StartPosLon, EndPosLat, EndPosLon, RealStartTime, RealEndTime, ClientId, Info, Priority, ScheduleId" 
					+ " FROM Tasks" 
					+ " WHERE _id = " + taskId;
     		Cursor c = db.rawQuery(query, null);
     		

     		if (!c.moveToFirst())
     			return null;
     		
     		CyclicTask result = new CyclicTask();
     		FillTaskFromCursor(c, result);
     		
     		query = "SELECT EmployeeId, TaskInterval"
     			+ " FROM EmployeeHasCyclicTasks"
     			+ " WHERE TaskId = " + taskId;
     		c = db.rawQuery(query, null);
     		if (!c.moveToFirst())
     			return null;
     		
     		result.EmployeeId = c.getInt(c.getColumnIndex("EmployeeId"));
     		result.TaskInterval = c.getInt(c.getColumnIndex("TaskInterval"));
      		    	    		  		
     		return result;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     	}
     	
		return null;
	}
	
	public List<CyclicTask> GetCyclicTaskList(int employeeId)
	{
     	try {
     		
     		String query = "SELECT TaskId" 
					+ " FROM EmployeeHasCyclicTasks" 
					+ " WHERE _id = " + employeeId;
     		Cursor c = db.rawQuery(query, null);
     		List<CyclicTask> result = new ArrayList<CyclicTask>();
     		if (!c.moveToFirst())
     			return result;

     		List<Integer> tmp = new ArrayList<Integer>();
	     	while (!c.isAfterLast()){    	     		
	     		tmp.add(c.getInt(c.getColumnIndex("TaskId")));
	         	c.moveToNext();
	     	}
	     	c.close();
	     	for (int id : tmp)
	         	result.add(GetCyclicTask(id));
	     	return result;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     	}
     	
		return null;
	}
	
	public void FillTaskFromCursor(Cursor c, Task t)
	{
 		t.Id = c.getInt(c.getColumnIndex("_id"));
 		t.CreatorId = c.getInt(c.getColumnIndex("CreatorId"));
 		t.ScheduleId = c.getInt(c.getColumnIndex("ScheduleId"));
 		int taskType = c.getInt(c.getColumnIndex("TaskTypeId"));
 		int taskStatus = c.getInt(c.getColumnIndex("TaskStatusId"));
 		t.ClientId = c.getInt(c.getColumnIndex("ClientId"));
 		t.Info = c.getString(c.getColumnIndex("Info"));
 		t.Priority = c.getInt(c.getColumnIndex("Priority"));
 		t.CreationDate = c.getString(c.getColumnIndex("CreationDate"));
 		t.ModificationDate = c.getString(c.getColumnIndex("ModificationDate"));
 		t.StartTime = c.getString(c.getColumnIndex("StartTime"));
 		t.EndTime = c.getString(c.getColumnIndex("EndTime"));
 		t.StartPositionLatitude = c.getDouble(c.getColumnIndex("StartPosLat"));
 		t.StartPositionLongitude = c.getDouble(c.getColumnIndex("StartPosLon"));
 		t.EndPositionLatitude = c.getDouble(c.getColumnIndex("EndPosLat"));
 		t.EndPositionLongitude = c.getDouble(c.getColumnIndex("EndPosLon"));
 		t.RealStartTime = c.getString(c.getColumnIndex("RealStartTime"));
 		t.RealEndTime = c.getString(c.getColumnIndex("RealEndTime")); 		
 		
 		c.close();
 		
 		t.TaskType = GetTaskType(taskType);
 		t.TaskStatus = GetTaskStatus(taskStatus);
	}
	
	public boolean StoreTask(Task task, int employeeId)
	{
     	try {
     		int result;
			ContentValues cv = new ContentValues();
			if (task.Id == 0){
				cv.put("CreationDate",task.CreationDate);
			}
			cv.put("CreatorId", task.CreatorId);
			if (task.TaskStatus != null)
				cv.put("TaskStatusId", task.TaskStatus.Id);
			else
				cv.putNull("TaskStatusId");
			if (task.TaskType != null)
				cv.put("TaskTypeId", task.TaskType.Id);
			else
				cv.putNull("TaskTypeId");
			cv.put("_id", task.Id);
			cv.put("ClientId", task.ClientId);
			cv.put("Info", task.Info);
			cv.put("Priority", task.Priority);
			cv.put("ScheduleId", task.ScheduleId);
			cv.put("EndPositionLatitude", task.EndPositionLatitude);
			cv.put("EndPositionLongitude", task.EndPositionLongitude);
			cv.put("EndTime", task.EndTime);
			cv.put("ModificationDate", task.ModificationDate);
			cv.put("RealEndTime", task.RealEndTime);
			cv.put("RealStartTime", task.RealStartTime);
			cv.put("StartPositionLatitude", task.StartPositionLatitude);
			cv.put("StartPositionLongitude", task.StartPositionLongitude);
			cv.put("StartTime", task.StartTime);
			
			result = db.update("Tasks", cv, "_id ="+task.Id, null);
			int taskId = task.Id;
			if (result == 0){
				taskId = (int)db.insert("Tasks", null, cv);
				result = taskId != -1 ? 1:0;
			}
     		
			if (taskId == -1)
				return false;
			Schedule schedule = null;
			
			int scheduleId = -1;
			if (task.ScheduleId != null)
			{
	     		String query = "SELECT _id" 
						+ " FROM Schedules" 
						+ " WHERE _id = " + task.ScheduleId;
	     		Cursor c = db.rawQuery(query, null);
	     		if (c.moveToFirst())
	     			schedule = GetSchedule(c.getInt(c.getColumnIndex("_id")));
	     		scheduleId = task.ScheduleId;
			}
			boolean isBeingAdded = false;
			if (schedule == null){
	     		String query = "SELECT _id" 
					+ " FROM Schedules" 
					+ " WHERE EmployeeId = " + employeeId + " and StartTime = "+task.StartTime;
	     		Cursor c = db.rawQuery(query, null);
	     		if (c.moveToFirst()){
	     			schedule = GetSchedule(c.getInt(c.getColumnIndex("_id")));
	     			scheduleId = schedule.Id;
	     		}
	     		
	     		if (schedule == null){
	     			isBeingAdded = true;
	     			cv = new ContentValues();
	     			
	     			cv.put("CreationDate", task.CreationDate);
	     			cv.put("StartTime", task.StartTime);
	     			cv.put("EndTime", task.EndTime);
	     			cv.put("EmployeeId", employeeId);
	     			cv.put("ModificationDate", task.ModificationDate);
	     			
					scheduleId =(int) db.insert("Schedules", null, cv);
					if (scheduleId == -1)
						throw new Exception("Faile to insert Schedules");
					cv = new ContentValues();
					cv.put("ScheduleId", (int)scheduleId);
					
					if (db.update("Tasks", cv, "_id = " + taskId, null) == 0)
						throw new Exception("Failed to update Task " + taskId);
	     		}
			}
			if (!isBeingAdded){
	     		String query = "SELECT _id" 
					+ " FROM Tasks" 
					+ " WHERE ScheduleId = " + scheduleId + " and StartTime < "+task.EndTime + " and EndTime >" + task.StartTime;
	     		Cursor c = db.rawQuery(query, null);
				boolean collide = c.getCount() != 0;

                if (collide)
                    throw new Exception("Task collides with schedule");

                // move schedule time boundries
                boolean update = false;
                if (Date.parse(schedule.StartTime) > Date.parse(task.StartTime)){ schedule.StartTime = task.StartTime; update = true; }
                if (Date.parse(schedule.EndTime) < Date.parse(task.EndTime)) { schedule.EndTime = task.EndTime;update = true; }
                if (update)
                	if (!StoreSchedule(schedule))
                		throw new Exception("Failed to store schedule");
			}
			return result == 1 ? true : false;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     		return false;
     	}
	}
	
	public boolean StoreCyclicTask(CyclicTask cyclicTask, int employeeId)
	{
     	try {
     		int result;
			ContentValues cv = new ContentValues();

			if (cyclicTask.Id == 0){
				cv.put("CreationDate",cyclicTask.CreationDate);
			}
			
			cv.put("CreatorId", cyclicTask.CreatorId);
			if (cyclicTask.TaskStatus != null)
				cv.put("TaskStatusId", cyclicTask.TaskStatus.Id);
			else
				cv.putNull("TaskStatusId");
			if (cyclicTask.TaskType != null)
				cv.put("TaskTypeId", cyclicTask.TaskType.Id);
			else
				cv.putNull("TaskTypeId");
			cv.put("_id", cyclicTask.Id);
			cv.put("ClientId", cyclicTask.ClientId);
			cv.put("Info", cyclicTask.Info);
			cv.put("Priority", cyclicTask.Priority);
			cv.put("ScheduleId", cyclicTask.ScheduleId);
			cv.put("EndPositionLatitude", cyclicTask.EndPositionLatitude);
			cv.put("EndPositionLongitude", cyclicTask.EndPositionLongitude);
			cv.put("EndTime", cyclicTask.EndTime);
			cv.put("ModificationDate", cyclicTask.ModificationDate);
			cv.put("RealEndTime", cyclicTask.RealEndTime);
			cv.put("RealStartTime", cyclicTask.RealStartTime);
			cv.put("StartPositionLatitude", cyclicTask.StartPositionLatitude);
			cv.put("StartPositionLongitude", cyclicTask.StartPositionLongitude);
			cv.put("StartTime", cyclicTask.StartTime);
			
			result = db.update("Tasks", cv, "_id ="+cyclicTask.Id, null);
			if (result == 0){
				long taskId = db.insert("Tasks", null, cv);
				result = taskId != -1 ? 1 : 0;
				cv = new ContentValues();
				cv.put("TaskId", (int)taskId);
				cv.put("EmployeeId", cyclicTask.EmployeeId);
				cv.put("TaskInterval", cyclicTask.TaskInterval);
				if (db.insert("EmployeeHasCyclicTasks", null, cv)==-1)
					throw new Exception("Failed to insert EmployeeHasCyclicTasks taskid " + taskId);
			}
			else{			
				cv = new ContentValues();
				cv.put("TaskId", cyclicTask.Id);
				cv.put("EmployeeId", cyclicTask.EmployeeId);
				cv.put("TaskInterval", cyclicTask.TaskInterval);
				if(db.update("EmployeeHasCyclicTasks", cv, "_id ="+cyclicTask.Id, null) == 0)
					throw new Exception("Failed to update EmployeeHasCyclicTasks, taskID:"+cyclicTask.Id);
			}
			
			return result == 1 ? true : false;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     		return false;
     	}
	}
	
	public boolean RemoveTask(int taskId)
	{
     	try {
     		int result;
			Task tmp = GetTask(taskId);
			result = db.delete("Tasks", "_id ="+taskId, null);
			if (tmp.ScheduleId != null && tmp.ScheduleId != 0){
				Schedule schedule = GetSchedule(tmp.ScheduleId);
				if (schedule.Tasks != null && schedule.Tasks.size() == 0)
					if (!RemoveSchedule(schedule.Id))
						throw new Exception("Failed to remove schedule, id " + schedule.Id);
				else
				{
					String newStartTime = schedule.Tasks.get(0).StartTime;
					String newEndTime = schedule.Tasks.get(0).EndTime;
					for (Task t : schedule.Tasks){
						if (Date.parse(t.StartTime) < Date.parse(newStartTime)){
							newStartTime = t.StartTime;
						}
						if (Date.parse(t.EndTime) > Date.parse(newEndTime)){
							newEndTime = t.EndTime;
						}
						
					}
					schedule.StartTime = newStartTime;
					schedule.EndTime = newEndTime;
					if (!StoreSchedule(schedule))
						throw new Exception("Failed to update Schedule, id: " + schedule.Id);
				}
			}
			return result == 1 ? true : false;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     		return false;
     	}
	}
	
	public boolean StartTask(int taskId, Date time, double latitude, double longitude)
	{
     	try {
     		int result;
			ContentValues cv = new ContentValues();
			
			cv.put("RealStartTime", time.toString());
			cv.put("StartPositionLatitude", latitude);
			cv.put("StartPositionLongitude", longitude);
			
			result = db.update("Tasks", cv, "_id ="+taskId, null);
			return result == 1 ? true : false;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     		return false;
     	}
	}

	public boolean EndTask(int taskId, Date time, double latitude, double longitude)
	{
     	try {
     		int result;
			ContentValues cv = new ContentValues();
			
			cv.put("RealEndTime", time.toString());
			cv.put("EndPositionLatitude", latitude);
			cv.put("EndPositionLongitude", longitude);
			
			result = db.update("Tasks", cv, "_id ="+taskId, null);
			return result == 1 ? true : false;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     		return false;
     	}
	}
	
	public List<TaskStatus> GetTaskStatusList()
	{
     	try {
     		
     		String query = "SELECT _id"
     						+ " FROM TaskStatus";
     		Cursor c = db.rawQuery(query, null);
     		
     		List<TaskStatus> result = new ArrayList<TaskStatus>();
     		if (!c.moveToFirst())
     			return result;
     		
     		List<Integer> tmp = new ArrayList<Integer>();
     		while (!c.isAfterLast()){
     			tmp.add(c.getInt(c.getColumnIndex("_id")));
     			c.moveToNext();
     		}
     		c.close();
     		for(int id : tmp)
     			result.add(GetTaskStatus(id));	
     		return result;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     	}
     	
		return null;
	}
	
	public TaskStatus GetTaskStatus(int taskStatusid)
	{
     	try {
     		
     		String query = "SELECT _id, Name, Description" 
							+ " FROM TaskStatus" 
							+ " WHERE _id = " + taskStatusid;
     		Cursor c = db.rawQuery(query, null);
     		

     		if (!c.moveToFirst())
     			return null;
     		
     		TaskStatus result = new TaskStatus();
     		result.Id = c.getInt(c.getColumnIndex("_id"));
     		result.Name = c.getString(c.getColumnIndex("Name"));
     		result.Description = c.getString(c.getColumnIndex("Description"));
     		    	    		  		
     		return result;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     	}
     	
		return null;
	}
	
	public boolean StoreTaskStatus(TaskStatus taskStatus)
	{
     	try {
     		int result;
			ContentValues cv = new ContentValues();

			cv.put("_id",taskStatus.Id);
			cv.put("Name",taskStatus.Name);
			cv.put("Description", taskStatus.Description);
			
			result = db.update("TaskStatus", cv, "_id ="+taskStatus.Id, null);
			if (result == 0)
				result = db.insert("TaskStatus", null, cv) != -1 ? 1 : 0;
			
			return result == 1 ? true : false;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     		return false;
     	}
	}
	
	public boolean RemoveTaskStatus(int taskStatusId)
	{
     	try {
     		int result;
			result = db.delete("TaskStatus", "_id ="+taskStatusId, null);
			return result == 1 ? true : false;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     		return false;
     	}
	}
	
	public List<TaskType> GetTaskTypeList()
	{
     	try {
     		
     		String query = "SELECT _id"
     						+ " FROM TaskTypes";
     		Cursor c = db.rawQuery(query, null);
     		
     		List<TaskType> result = new ArrayList<TaskType>();
     		if (!c.moveToFirst())
     			return result;
     		
     		List<Integer> tmp = new ArrayList<Integer>();
     		while (!c.isAfterLast()){
     			tmp.add(c.getInt(c.getColumnIndex("_id")));
     			c.moveToNext();
     		}
     		c.close();
     		for (int id: tmp)
     			result.add(GetTaskType(id));
     		return result;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     	}
     	
		return null;
	}
	
	public TaskType GetTaskType(int taskTypeId)
	{
     	try {
     		
     		String query = "SELECT _id, Name, Description" 
							+ " FROM TaskTypes" 
							+ " WHERE _id = " + taskTypeId;
     		Cursor c = db.rawQuery(query, null);
     		

     		if (!c.moveToFirst())
     			return null;
     		
     		TaskType result = new TaskType();
     		result.Id = c.getInt(c.getColumnIndex("_id"));
     		result.Name = c.getString(c.getColumnIndex("Name"));
     		result.Description = c.getString(c.getColumnIndex("Description"));
     		    	    		  		
     		return result;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     	}
     	
		return null;
	}
	
	public boolean StoreTaskType(TaskType taskType)
	{
     	try {
     		int result;
			ContentValues cv = new ContentValues();

			cv.put("_id", taskType.Id);
			cv.put("Name",taskType.Name);
			cv.put("Description", taskType.Description);
			
			result = db.update("TaskTypes", cv, "_id ="+taskType.Id, null);
			if (result == 0)
				result = db.insert("TaskTypes", null, cv) != -1 ? 1: 0;
			
			return result == 1 ? true : false;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     		return false;
     	}
	}
	
	public boolean RemoveTaskTypes(int taskTypeId)
	{
     	try {
     		int result;
			result = db.delete("TaskTypes", "_id ="+taskTypeId, null);
			return result == 1 ? true : false;
     	}
     	catch(SQLException sqle) {
     		Log.d(this.getClass().getName() ,sqle.getMessage());
     		throw sqle;
     	}catch (Exception e){
     		Log.d(this.getClass().getName(), e.getMessage());
     		return false;
     	}
	}
}
